package com.coolxiaoyao.web.filter;

import com.coolxiaoyao.common.exception.HttpForbiddenException;
import com.coolxiaoyao.common.exception.HttpNotFoundException;
import com.coolxiaoyao.web.http.Filter;
import io.netty.handler.codec.http.HttpHeaders;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Pattern;

/**
 * @author Kerry on 19/07/23
 */

public class IPFilter extends Filter {

    private List<String> ipList = new ArrayList<>();
    private List<Pattern> ipPattern = new ArrayList<>();

    public IPFilter() {
    }

    public IPFilter(List<String> ipList) {
        this.ipList.addAll(ipList);
    }

    public IPFilter(List<String> ipList, List<String> ipPatterStr) {
        this.ipList.addAll(ipList);
        for (String patternStr : ipPatterStr) {
            Pattern compile = Pattern.compile(patternStr);
            ipPattern.add(compile);
        }
    }

    @Override
    public Object filter(HttpHeaders httpHeaders) throws Exception {
        if (httpHeaders == null) {
            throw new HttpForbiddenException("403");
        }
        final String host = httpHeaders.get("HOST");
        return host;
    }

    public void addIp(String... ip) {
        ipList.addAll(Arrays.asList(ip));
    }

    public void addPattern(String... patterns) {
        for (String pattern : patterns) {
            final Pattern compile = Pattern.compile(pattern);
            ipPattern.add(compile);
        }
    }

}
